package bootstrap

import (
	"app/config"
	"app/internal/consts"
	"app/internal/middleware"
	"github.com/gin-gonic/gin"
	"io"
	"os"
)

var Routers = make([]func(engine *gin.Engine), 0)

func RegisterHttpRouter(r ...func(engine *gin.Engine)) {
	Routers = append(Routers, r...)
}

// initHttpEngine 初始化http引擎
func NewHttpRouter(app *config.AppConfig) *gin.Engine {
	//根据环境对gin进行配置
	ginWithEnv(app.Env)
	//创建一个gin引擎
	r := gin.New()
	//调试模式下开启中间件
	if app.Debug {
		//日志中间件
		r.Use(gin.Logger())
		//Hack 中间件
		//r.Use(middleware.Hack(18))
	}
	//开启全局中间件,业务中间件在 `BizRouterRegister` 中进行注册
	{
		r.Use(middleware.CorsHandler())    //跨域中间件
		r.Use(middleware.RequestHandler()) //请求预处理中间件,增加request_id
		r.Use(middleware.RecoverHandler()) //异常捕获中间件
	}
	//注册路由
	for _, f := range Routers {
		f(r)
	}
	// set up trusted agents
	_ = r.SetTrustedProxies([]string{"*"})

	return r
}

// ginWithEnv 根据环境变量定义
func ginWithEnv(env string) {
	//如果匹配不到就认为是dev模式
	switch env {
	case consts.ENV_TEST:
		gin.SetMode(gin.TestMode)
		gin.DefaultWriter = io.Discard
	case consts.ENV_PROD:
		gin.SetMode(gin.ReleaseMode)
		gin.DefaultWriter = io.Discard
	default:
		gin.SetMode(gin.DebugMode)
		gin.DefaultWriter = os.Stdout
		gin.ForceConsoleColor()
	}
}
